import 'package:awak/common/values/svg.dart';
import 'package:beamer/beamer.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:awak/bloc/auth/auth_bloc.dart';
import 'package:awak/bloc/auth/auth_event.dart';
import 'package:awak/bloc/auth/auth_state.dart';
import 'package:awak/common/models/today_goal.dart';
import 'package:awak/common/utils/util_text.dart';
import 'package:awak/common/values/images.dart';



class AddGoalPage extends StatefulWidget {
  const AddGoalPage({Key? key}) : super(key: key);

  @override
  State<AddGoalPage> createState() => _AddGoalPageState();
}

class _AddGoalPageState extends State<AddGoalPage> with TickerProviderStateMixin {
  bool _isTodayGoalExpanded = true;
  bool _isTargetPoolExpanded = true;
  final TextEditingController _targetController = TextEditingController();

  // TodayGoal相关状态
  List<TodayGoal> _todayGoals = [];
  List<String> _targetPoolGoals = [
    'Buy Birthday Present',
    'Prepare A Meal',
    'Complete Work Summary',
    'Water The Plants',
    'Drink 1.5 Liters Of Water',
    'Watch A Movie',
  ];

  // 用于跟踪新增和删除的目标
  List<String> _newGoals = [];
  List<int> _deletedGoalIds = [];

  late AnimationController _todayGoalAnimationController;
  late AnimationController _targetPoolAnimationController;
  late Animation<double> _todayGoalAnimation;
  late Animation<double> _targetPoolAnimation;

  @override
  void initState() {
    super.initState();

    // 初始化动画控制器
    _todayGoalAnimationController = AnimationController(
      duration: const Duration(milliseconds: 300),
      vsync: this,
    );

    _targetPoolAnimationController = AnimationController(
      duration: const Duration(milliseconds: 300),
      vsync: this,
    );



    // 初始化动画
    _todayGoalAnimation = CurvedAnimation(
      parent: _todayGoalAnimationController,
      curve: Curves.easeInOut,
    );

    _targetPoolAnimation = CurvedAnimation(
      parent: _targetPoolAnimationController,
      curve: Curves.easeInOut,
    );

    // 设置初始状态
    if (_isTodayGoalExpanded) {
      _todayGoalAnimationController.value = 1.0;
    }
    if (_isTargetPoolExpanded) {
      _targetPoolAnimationController.value = 1.0;
    }

    // 加载TodayGoal数据
    _loadTodayGoals();
  }

  void _loadTodayGoals() {
    final currentUser = context.read<AwakBloc>().userRepository.currentUser;
    if (currentUser != null) {
      context.read<AwakBloc>().add(FetchTodayGoalsEvent(currentUser.id!));
    }
  }

  void _addGoalFromPool(String goalName) {
    setState(() {
      _newGoals.add(goalName);
      _targetPoolGoals.remove(goalName);
    });
  }

  void _removeGoalFromToday(TodayGoal goal) {
    setState(() {
      if (goal.id != null) {
        _deletedGoalIds.add(goal.id!);
      }
      _todayGoals.remove(goal);
    });
  }

  void _removeNewGoal(String goalName) {
    setState(() {
      _newGoals.remove(goalName);
      _targetPoolGoals.add(goalName);
    });
  }

  void _addCustomGoal() {
    final goalName = _targetController.text.trim();
    if (goalName.isNotEmpty && goalName.length <= 25) {
      setState(() {
        _newGoals.add(goalName);
        _targetController.clear();
      });
    }
  }

  void _saveGoals() {
    final currentUser = context.read<AwakBloc>().userRepository.currentUser;
    if (currentUser != null) {
      // 删除已标记删除的目标
      if (_deletedGoalIds.isNotEmpty) {
        context.read<AwakBloc>().add(DeleteTodayGoalsByIdsEvent(_deletedGoalIds));
      }

      // 添加新目标
      for (String goalName in _newGoals) {
        final newGoal = TodayGoal(
          name: goalName,
          userId: currentUser.id!,
        );
        context.read<AwakBloc>().add(CreateTodayGoalEvent(newGoal));
      }
    }

    // 返回上一页
    Beamer.of(context).beamBack();
  }

  Map<String, Color> _getGoalColors(int index) {
    final colorSets = [
      {
        'background': Color(0xFFFEF463),
        'border': Color(0xFFD9B747),
      },
      {
        'background': Color(0xFFD3F524),
        'border': Color(0xFF89B72D),
      },
      {
        'background': Colors.white,
        'border': Color(0xFFB3B3B3),
      },
    ];
    return colorSets[index % colorSets.length];
  }

  @override
  Widget build(BuildContext context) {
    return BlocListener<AwakBloc, AwakState>(
      listener: (context, state) {
        if (state is TodayGoalsLoaded) {
          setState(() {
            _todayGoals = state.todayGoals;
          });
        }
      },
      child: Scaffold(
        body: Stack(
          children: [
            // 背景图片 - 最底层
            Positioned.fill(
              child: Container(
                decoration: BoxDecoration(
                  image: DecorationImage(
                    image: AssetImage(AwakImages.editBg),
                    fit: BoxFit.cover,
                  ),
                ),
              ),
            ),
            // 内容层
            SafeArea(
              child: Column(
                children: [
                  Expanded(
                    child: SingleChildScrollView(
                      child: Column(
                        children: [
                          SizedBox(height: 20.h),
                          // 顶部操作栏
                          Row(
                            children: [
                              SizedBox(width: 16.w),
                              GestureDetector(
                                onTap: () {
                                  Beamer.of(context).beamBack();
                                },
                                child: Icon(
                                  AwakSvg.back,
                                  size: 22.sp,
                                  color: Colors.black,
                                ),
                              ),
                              Expanded(
                                child: Center(
                                  child: Text(
                                    'NEW TARGET',
                                    style: AwakText.body16Style.copyWith(
                                      fontSize: 20.sp,
                                      fontWeight: FontWeight.bold,
                                      color: Colors.black,
                                    ),
                                  ),
                                ),
                              ),
                              SizedBox(width: 40.w),
                            ],
                          ),

                          SizedBox(height: 20.h),

                          // Today's Goal 部分
                          _buildTodayGoalSection(),

                          // Target Pool 部分
                          _buildTargetPoolSection(),

                          // 底部padding，避免被按钮遮挡
                          SizedBox(height: 100.h),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
            // 底部固定按钮 - 最顶层
            Positioned(
              left: 0,
              right: 0,
              bottom: 0,
              child: Container(
                padding: EdgeInsets.fromLTRB(16.w, 16.h, 16.w, 34.h),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(20.r),
                    topRight: Radius.circular(20.r),
                  ),
                ),
                child: GestureDetector(
                  onTap: _saveGoals,
                  child: Container(
                    width: double.infinity,
                    height: 44.h,
                    decoration: BoxDecoration(
                      color: const Color(0xFFB6F558),
                      borderRadius: BorderRadius.circular(12.r),
                    ),
                    child: Center(
                      child: Text(
                        'Save',
                        style: AwakText.body16Style.copyWith(
                          fontSize: 16.sp,
                          fontWeight: FontWeight.w600,
                          color: Colors.black,
                        ),
                      ),
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  // Today's Goal 部分
  Widget _buildTodayGoalSection() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 14.w),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(12.r),
      ),
      child: Column(
        children: [
          // 标题栏
          GestureDetector(
            onTap: () {
              setState(() {
                _isTodayGoalExpanded = !_isTodayGoalExpanded;
                if (_isTodayGoalExpanded) {
                  _todayGoalAnimationController.forward();
                } else {
                  _todayGoalAnimationController.reverse();
                }
              });
            },
            child: Container(
              padding: EdgeInsets.symmetric(vertical: 12.h),
              child: Row(
                children: [
                  Text(
                    "Today's Goal",
                    style: TextStyle(
                      fontSize: 18.sp,
                      fontWeight: FontWeight.bold,
                      color: Colors.black,
                    ),
                  ),
                  SizedBox(width: 8.w),
                  Text(
                    '(${_todayGoals.length + _newGoals.length})',
                    style: TextStyle(
                      color: Colors.black,
                      fontSize: 18.sp,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  const Spacer(),
                  AnimatedBuilder(
                    animation: _todayGoalAnimation,
                    builder: (context, child) {
                      return Transform.rotate(
                        angle: _todayGoalAnimation.value * 3.14159, // 180度旋转
                        child: Icon(
                          Icons.keyboard_arrow_down,
                          color: Colors.black,
                          size: 24.sp,
                        ),
                      );
                    },
                  ),
                ],
              ),
            ),
          ),
          // 可折叠内容
          SizeTransition(
            sizeFactor: _todayGoalAnimation,
            child: _buildTodayGoalContent(),
          ),
        ],
      ),
    );
  }

  // Today's Goal 内容
  Widget _buildTodayGoalContent() {
    List<Widget> goalChips = [];

    // 添加现有的TodayGoal
    for (int i = 0; i < _todayGoals.length; i++) {
      final goal = _todayGoals[i];
      final colors = _getGoalColors(i);

      goalChips.add(Container(
        padding: EdgeInsets.symmetric(
          horizontal: 12.w,
          vertical: 8.h,
        ),
        decoration: BoxDecoration(
          color: colors['background'],
          borderRadius: BorderRadius.circular(100.r),
          border: Border.all(
            color: colors['border']!,
            width: 1.w,
          ),
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(
              goal.name,
              style: AwakText.body14Style.copyWith(
                fontWeight: FontWeight.w500,
                fontSize: 14.sp,
              ),
            ),
            SizedBox(width: 8.w),
            GestureDetector(
              onTap: () => _removeGoalFromToday(goal),
              child: Icon(
                Icons.close,
                size: 16.w,
                color: Colors.grey[600],
              ),
            ),
          ],
        ),
      ));
    }

    // 添加新增的目标
    for (int i = 0; i < _newGoals.length; i++) {
      final goalName = _newGoals[i];
      final colors = _getGoalColors(i);

      goalChips.add(Container(
        padding: EdgeInsets.symmetric(
          horizontal: 12.w,
          vertical: 8.h,
        ),
        decoration: BoxDecoration(
          color: colors['background'],
          borderRadius: BorderRadius.circular(100.r),
          border: Border.all(
            color: colors['border']!,
            width: 1.w,
          ),
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(
              goalName,
              style: AwakText.body14Style.copyWith(
                fontWeight: FontWeight.w500,
                fontSize: 14.sp,
              ),
            ),
            SizedBox(width: 8.w),
            GestureDetector(
              onTap: () => _removeNewGoal(goalName),
              child: Icon(
                Icons.close,
                size: 16.w,
                color: Colors.grey[600],
              ),
            ),
          ],
        ),
      ));
    }

    return Padding(
      padding: EdgeInsets.fromLTRB(0, 0, 0, 16.h),
      child: goalChips.isEmpty
        ? Center(
            child: Text(
              'No goals added yet',
              style: AwakText.body14Style.copyWith(
                fontSize: 14.sp,
                color: Colors.grey[600],
              ),
            ),
          )
        : Wrap(
            spacing: 8.w,
            runSpacing: 8.h,
            children: goalChips,
          ),
    );
  }

  // Target Pool 部分
  Widget _buildTargetPoolSection() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 14.w),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(12.r),
      ),
      child: Column(
        children: [
          // 标题栏
          GestureDetector(
            onTap: () {
              setState(() {
                _isTargetPoolExpanded = !_isTargetPoolExpanded;
                if (_isTargetPoolExpanded) {
                  _targetPoolAnimationController.forward();
                } else {
                  _targetPoolAnimationController.reverse();
                }
              });
            },
            child: Container(
              padding: EdgeInsets.symmetric(vertical: 12.h),
              child: Row(
                children: [
                  Text(
                    "Target Pool",
                    style: TextStyle(
                      fontSize: 18.sp,
                      fontWeight: FontWeight.bold,
                      color: Colors.black,
                    ),
                  ),
                  const Spacer(),
                  AnimatedBuilder(
                    animation: _targetPoolAnimation,
                    builder: (context, child) {
                      return Transform.rotate(
                        angle: _targetPoolAnimation.value * 3.14159,
                        child: Icon(
                          Icons.keyboard_arrow_down,
                          color: Colors.black,
                          size: 24.sp,
                        ),
                      );
                    },
                  ),
                ],
              ),
            ),
          ),
          // 可折叠内容
          SizeTransition(
            sizeFactor: _targetPoolAnimation,
            child: _buildTargetPoolContent(),
          ),
        ],
      ),
    );
  }

  // Target Pool 内容
  Widget _buildTargetPoolContent() {
    return Padding(
      padding: EdgeInsets.fromLTRB(0, 0, 0, 16.h),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 0.w),
            child: Text(
              'Example:',
              style: AwakText.body14Style.copyWith(
                fontSize: 14.sp,
                color: Colors.grey[600],
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
          SizedBox(height: 12.h),
          Wrap(
            spacing: 8.w,
            runSpacing: 8.h,
            children: _targetPoolGoals.map((goalName) {
              return Container(
                padding: EdgeInsets.symmetric(
                  horizontal: 12.w,
                  vertical: 8.h,
                ),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(100.r),
                ),
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text(
                      goalName,
                      style: AwakText.body14Style.copyWith(
                        fontWeight: FontWeight.w500,
                        fontSize: 14.sp,
                      ),
                    ),
                    SizedBox(width: 8.w),
                    GestureDetector(
                      onTap: () => _addGoalFromPool(goalName),
                      child: Icon(
                        Icons.add,
                        size: 16.w,
                        color: Colors.grey[600],
                      ),
                    ),
                  ],
                ),
              );
            }).toList(),
          ),
          SizedBox(height: 16.h),
          // 输入框和按钮
          Row(
            children: [
              Expanded(
                child: Container(
                  padding: EdgeInsets.symmetric(vertical: 6.h),
                  height: 40.h,
                  decoration: BoxDecoration(
                    color: Colors.white.withValues(alpha: 0.7),
                    borderRadius: BorderRadius.circular(20.r),
                  ),
                  child: TextField(
                    controller: _targetController,
                    decoration: InputDecoration(
                      hintText: 'Enter Target, No More 5 Characters',
                      hintStyle: AwakText.body14Style.copyWith(
                        fontSize: 12.sp,
                        color: Colors.grey[500],
                      ),
                      border: InputBorder.none,
                      contentPadding: EdgeInsets.symmetric(
                          horizontal: 16.w, vertical: 10.h),
                    ),
                    style: AwakText.body14Style.copyWith(fontSize: 14.sp),
                  ),
                ),
              ),
              SizedBox(width: 12.w),
              GestureDetector(
                onTap: _addCustomGoal,
                child: Container(
                  height: 40.h,
                  padding: EdgeInsets.symmetric(horizontal: 10.w),
                  decoration: BoxDecoration(
                    color: const Color(0xFFB6F558),
                    borderRadius: BorderRadius.circular(20.r),
                  ),
                  child: Center(
                    child: Text(
                      'Set A Goal',
                      style: AwakText.body14Style.copyWith(
                        color: Colors.black,
                        fontSize: 12.sp,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }



  @override
  void dispose() {
    _todayGoalAnimationController.dispose();
    _targetPoolAnimationController.dispose();
    _targetController.dispose();
    super.dispose();
  }
}
